#include "entertainment.h"


dispatch_t dispatch_table[] = {
	{"AddApplication", NULL},
	{"RemoveApplication", NULL},
	{"AddDetails", NULL},
	{"UsedCount", NULL},
	{"AddScoreToGame", NULL},
	{"Report", NULL},
	{NULL, NULL}
};


int tokenize(char * buf, char ** tokens, int max_tokens)
{
	int i;
	int j = 0;
	enum {TRUE = 1, FALSE = 0} whitespace = TRUE;
	
	for (i = 0; buf[i] != '\0'; i++)
	{
		if (buf[i] == ' ' || buf[i] == '\t' || buf[i] == '\n')
		{
			buf[i] = '\0';
			whitespace = TRUE;
		}
		else if (whitespace)
		{
			if (j > max_tokens)
				break;
			tokens[j] = &buf[i];
			j++;
			whitespace = FALSE;
		}
	}
	
	return j;
}


result_t dispatch(FILE * outstream, int cnt, char ** tokens)
{
	int i;
	
	for (i = 0; dispatch_table[i].keyword != NULL; i++)
	{
		if (strcmp(tokens[0], dispatch_table[i].keyword) != 0)
			continue;
		return dispatch_table[i].func(outstream, &tokens[1]);
	}
	
	/* UNREPORTABLE ERROR: unknown command */
	return RES_ERROR;
}


result_t process_file(FILE * instream, FILE * outstream)
{
	char linebuf[MAX_LINE_SIZE];
	char tokens[MAX_TOKENS][MAX_TOKEN_SIZE];
	int cnt;
	
	while (!feof(instream))
	{
		if (fgets(linebuf, MAX_LINE_SIZE, instream) == NULL)
			/* UNREPORTABLE ERROR: error reading stream */
			return RES_FATAL;
		
		/* tokenize line, skip if empty or comment */
		cnt = tokenize(linebuf, tokens, MAX_TOKENS);
		if (cnt == 0)
			continue;
		if (tokens[0][0] == ';')
			continue;
		if (dispatch(outstream, cnt, tokens) == RES_FATAL)
			return RES_FATAL;
	}
	
	return RES_SUCCESS;
}



